package main

import (
	"fmt"
	"time"
	"sync"
)

type atomic struct {
	value 	int
	// 锁
	lock 	sync.Mutex
}

func (a *atomic) increment(){
	fmt.Println("safe")
	// 这个地方的精妙之处在于 用匿名函数配合defer 使得整个代码块都是安全的
	func(){
		a.lock.Lock()
		defer a.lock.Unlock()
		a.value++
	}()

}

func (a *atomic) get() int{
	return int(a.value)
}

func main() {
	var a atomic
	a.increment()
	go func() {
		a.increment()
	}()
	time.Sleep(time.Second)
	fmt.Println(a.value)
}
